package com.glb.gilibuy.web.mall;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.glb.gilibuy.entity.Product;
import com.glb.gilibuy.entity.UserOrder;
import com.glb.gilibuy.entity.UserReceiveAddress;
import com.glb.gilibuy.util.MapGenerator;
import com.glb.gilibuy.web.BaseController;
import com.glb.gilibuy.web.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description:
 * @Author: Yupeng Zhang
 * @Date: 2021-08-06 9:25
 */
@Api(tags = "订单模块")
@Controller
@RequestMapping("/user")
public class OrderCotroller extends BaseController {
    @ApiOperation(value = "结算后生成订单", notes = "结算后生成订单，修改库存", produces = "application/json")
    @PostMapping("/createOrder")
    @ResponseBody
    public Map<String, Object> createOrder(@RequestParam("addressId") String addressId,
                                           HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        String userId = userTemp.getUserId();
        Map<String, Object> cartRes = (Map<String, Object>) httpSession.getAttribute("cartRes");
        if (cartRes == null) {
            return MapGenerator.getRes(500, "未结算，不能生成订单！");
        }
        Map<String, Object> res = orderService.createOrder(cartRes, addressId, userId);
        if (res != null) {
            httpSession.removeAttribute("cartRes");
        }
        return res;
    }

    @ApiOperation(value = "获取订单列表", notes = "获取订单列表(可根据状态分类)", produces = "application/json")
    @GetMapping("/orderList")
    @ResponseBody
    public Map<String, Object> getOrderList(//订单状态默认值为999，表示查询全部订单；其他值表示查询相应状态的订单，
                                            //状态码：0->待付款；1->已付款，待发货；2->发货完成，已出库，待收货；3->已确认收货，交易成功，待评价；4->已评价；
                                            //-1->用户关闭；-2->超时关闭；-3->管理员关闭
                                            @RequestParam(value = "state", defaultValue = "999") Integer state,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        //每页6个
        PageHelper.startPage(page, 6);
        PageInfo pageInfo = orderService.findOrdersByUserIdAndState(userTemp.getUserId(), state);
        if (pageInfo != null) {
            return MapGenerator.getResWithData(200, "获取订单列表成功！", pageInfo);
        } else {
            return MapGenerator.getRes(201, "获取结果为空！");
        }
    }

    @ApiOperation(value = "获取单个订单(订单详情)", notes = "获取单个订单(订单详情)", produces = "application/json")
    @GetMapping("/order")
    @ResponseBody
    public Map<String, Object> getOrder(@RequestParam("orderId") String orderId,
                                        HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userTemp.getUserId());
        userOrder.setOrderId(orderId);

        return orderService.getOrder(userOrder);
    }

    @ApiOperation(value = "取消订单", notes = "取消订单，修改库存", produces = "application/json")
    @PostMapping("/cancelOrder")
    @ResponseBody
    public Map<String, Object> cancelOrder(@RequestParam("orderId") String orderId,
                                           HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");

        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userTemp.getUserId());
        userOrder.setOrderId(orderId);

        return orderService.cancelOrder(userOrder);
    }

    @ApiOperation(value = "确认收货", notes = "确认收货", produces = "application/json")
    @PostMapping("/confirmOrder")
    @ResponseBody
    public Map<String, Object> confirmOrder(@RequestParam("orderId") String orderId,
                                            HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");

        UserOrder userOrder = new UserOrder();
        userOrder.setOrderId(userTemp.getUserId());
        userOrder.setOrderId(orderId);

        return orderService.confirmOrder(userOrder);
    }

    @ApiOperation(value = "使用默认地址直接购买生成订单(停用)", notes = "使用默认地址直接购买一种商品并生成订单，不影响库存(停用)", produces = "application/json")
    @PostMapping("/createOrderByProduct")
    @ResponseBody
    public Map<String, Object> createOrderByProduct(@RequestParam("productId") String productId,
                                                    @RequestParam(value = "amount", defaultValue = "1") int amount,
                                                    HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        String userId = userTemp.getUserId();

        if (StringUtils.isEmpty(productId)) {
            return MapGenerator.getRes(500, "请输入商品编号！");
        }
        if (amount < 0 || (amount % 1 != 0)) {
            return MapGenerator.getRes(500, "请输入合法的数量！");
        }

        //找商品
        Product product = productService.selectProductByProductId(productId);

        if (product == null) {
            return MapGenerator.getRes(500, "商品编号不存在！");
        }

        //找用户默认地址
        UserReceiveAddress address = userReceiveAddressService.selectDefaultAddress(userId);
        if (address == null) {
            return MapGenerator.getRes(500, "请设置默认地址！");
        }
        //生成订单
        UserOrder userOrder = new UserOrder();
        //添加用户名
        userOrder.setUserId(userId);
        //添加地址至订单
        userOrder.setReceiveAddressDetail(address.getReceiveAddressDetail());
        userOrder.setReceiveCity(address.getReceiveCity());
        userOrder.setReceiveName(address.getReceiveName());
        userOrder.setReceivePhone(address.getReceivePhone());
        userOrder.setReceiveProvince(address.getReceiveProvince());
        userOrder.setReceiveRegion(address.getReceiveRegion());

        //添加状态
        //订单状态为未支付
        userOrder.setOrderState(0);
        //支付状态为未支付
        userOrder.setPaymentType(0);
        //单价乘以数量
        userOrder.setOrderPrice(product.getProductPrice().multiply(BigDecimal.valueOf(amount)));

        //保存订单

        userOrder = orderService.addOrder(userOrder);

        //保存订单内容
        orderItemService.addOrderItem(userOrder.getOrderId(), productId, product.getProductPrice(), Integer.valueOf(amount));

        return MapGenerator.getRes(200, "直接生成订单成功！");
    }

    @ApiOperation(value = "订单物流更新(停用)", notes = "订单物流更新(停用)", produces = "application/json")
    @PostMapping("/addTrackingNumber")
    @ResponseBody
    public Map<String, Object> addTrackingNumber(@RequestParam("orderId") String orderId,
                                                 @RequestParam("trackingNumber") String trackingNumber) {
        if (StringUtils.isEmpty(orderId)) {
            return MapGenerator.getRes(500, "请输入商品编号！");
        }
        if (StringUtils.isEmpty(trackingNumber)) {
            return MapGenerator.getRes(500, "请输入物流单号！");
        }
        if (orderService.addTrackingNumberToOrder(orderId, trackingNumber) > 0) {
            return MapGenerator.getRes(200, "物流单号添加成功！");
        }
        return MapGenerator.getRes(500, "添加物流单号失败！");
    }

}
